package com.sz.app.oss.api.logistics.order;

import com.sz.app.oss.constants.MessagesCodes;
import com.sz.app.oss.constants.Permissions;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.logistics.ord.dto.OrdOrderTrackAddDto;
import com.sz.biz.logistics.ord.dto.OrdOrderTrackingDto;
import com.sz.biz.logistics.ord.dto.SubOrderTrackingDto;
import com.sz.biz.logistics.ord.dto.TrackingSupOrder;
import com.sz.biz.logistics.ord.entity.OrdOrderTracking;
import com.sz.biz.logistics.ord.service.OrdOrderTrackingService;
import com.sz.biz.logistics.ord.service.impl.OrdTrackingResult;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.utils.EntityUtils;
import com.sz.common.base.utils.ObjectUtils;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.system.entity.SysDict;
import com.sz.common.core.system.service.SysDictService;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Function: 产品订单跟踪 controller <br>
 * Author: hpeng.wang <br>
 * Date: 2017-03-31 14:28:00
 */
@RestController
@RequestMapping("/api/v1/order/tracking")
@Api(description = " ", tags = "036-003、订单-物流")
public class OrdOrderTrackingController extends BaseController {
    @Autowired
    private OrdOrderTrackingService service;

    @Autowired
    private SysDictService sysDictService;

    /**
     * 新增物流信息
     *
     * @param trackingSupOrder 要保存的物流信息集合
     * @return
     */
    @ApiOperation(value = "新增", notes = "新增订单跟踪<br>权限：" + Permissions.BIZ_MGT_ORD_LOGISTICS)
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public ResultDto save(@RequestBody @ApiParam(value = "要保存的数据", required = true) @Validated TrackingSupOrder trackingSupOrder) {
        OrdTrackingResult trackingResult ;
        trackingResult = service.processAfterTracking(trackingSupOrder);
        ResultDto result = new ResultDto();
        if(!ObjectUtils.isEmpty(trackingResult)){
            if(trackingResult.isSuccess()){
                result.setMsg("添加物流消息成功");
            }else{
                result.setErrorCode(trackingResult.getReason());
                result.setMsg("添加物流消息失败"+trackingResult.getReason()+":"+trackingResult.getReasonContent());
            }
        }
        result.setData(trackingResult);
        return result;
    }


    /**
     * 新增一条系统给某个供应商的订单信息,页面表现为修改订单后，手动给某个供应商下发订单的信息
     *
     * @param waybillNo
     * @param serviceUid
     * @return
     */
    @ApiOperation(value = "人工修改订单信息之后，手动给服务商-供应商发消息", notes = "手动给服务商-供应商发消息<br>权限：" + Permissions.BIZ_MGT_ORD_LOGISTICS)
    @RequestMapping(value = "/{waybillNo}/services/{serviceUid}/{supplierId}", method = {RequestMethod.POST})
    @RequiresPermissions(Permissions.BIZ_MGT_ORD_LOGISTICS)
    public ResultDto addMsgAfterUpdateOrder(@ApiParam(value = "订单号", required = true) @PathVariable String waybillNo, @ApiParam(value = "服务商uid", required = true) @PathVariable String serviceUid, @ApiParam(value = "供应商id", required = true) @PathVariable Integer supplierId) {
        service.addMsgAfterUpdateOrder(waybillNo, serviceUid, supplierId);
        ResultDto result = getSaveSuccessDto(MessagesCodes.MODULE_ORDER_TRACKING);
        return result;
    }

    @ApiOperation(value = "人工补充子单的物流信息之后，手动给服务商-供应商发消息", notes = "手动给服务商-供应商发消息<br>权限：" + Permissions.BIZ_MGT_ORD_LOGISTICS)
    @RequestMapping(value = "/{waybillNo}/{subOrderNo}/services/{serviceUid}/{supplierId}", method = {RequestMethod.POST})
    @RequiresPermissions(Permissions.BIZ_MGT_ORD_LOGISTICS)
    public ResultDto addMsgAfterAddSubTracking(@ApiParam(value = "订单号", required = true) @PathVariable String waybillNo, @ApiParam(value = "子单号", required = true) @PathVariable String subOrderNo, @ApiParam(value = "服务商uid", required = true) @PathVariable String serviceUid, @ApiParam(value = "供应商id", required = true) @PathVariable Integer supplierId) {
        service.addMsgAfterAddSubTracking(waybillNo, subOrderNo, serviceUid, supplierId);
        ResultDto result = getSaveSuccessDto(MessagesCodes.MODULE_ORDER_TRACKING);
        return result;
    }


    /**
     * 批量删除
     *
     * @param ids 要删除的id集合
     * @return 操作结果
     */
    @ApiOperation(value = "删除", notes = "根据指定id集合删除数据<br>权限：" + Permissions.BIZ_MGT_ORD_LOGISTICS, httpMethod = "POST")
    @RequestMapping(value = "/deletions", method = {RequestMethod.POST})
    @RequiresPermissions(Permissions.BIZ_MGT_ORD_LOGISTICS)
    public ResultDto batchDelete(@RequestBody @ApiParam(value = "要删除的id集合", required = true) List<Integer> ids) {
        service.batchDelete(ids);
        ResultDto dto = getDeleteSuccessDto(MessagesCodes.MODULE_ORDER_TRACKING);
        return dto;
    }

    @ApiOperation(value = "增加子单物流信息", notes = "增加子单物流信息<br>权限：" + Permissions.BIZ_MGT_ORD_LOGISTICS, httpMethod = "POST")
    @RequestMapping(value = "/subs", method = {RequestMethod.POST})
    @RequiresPermissions(Permissions.BIZ_MGT_ORD_LOGISTICS)
    public ResultDto addSubTracking(@RequestBody @ApiParam(value = "子单物流消息dto") SubOrderTrackingDto dto) {
        service.addSubTracking(dto);
        ResultDto result = getSaveSuccessDto(MessagesCodes.MODULE_ORDER_TRACKING);
        return result;
    }

    @ApiOperation(value = "增加物流信息", notes = "增加物流信息<br>权限：" + Permissions.BIZ_MGT_ORD_LOGISTICS, httpMethod = "POST")
    @RequestMapping(value = "/add", method = {RequestMethod.POST})
    @RequiresPermissions(Permissions.BIZ_MGT_ORD_LOGISTICS)
    public ResultDto addTracking(@RequestBody @ApiParam(value = "物流消息dto") @Validated OrdOrderTrackAddDto dto) {
        List<String> noExistList = service.addTracking(dto.getContentList(), dto.getCode(), dto.getParams(), dto.getMessageTime(), dto.getType());
        ResultDto result = getOperateSuccessDto(MessagesCodes.MODULE_ORDER_TRACKING_UPGRADE);
        result.setData(noExistList);
        return result;
    }


    /**
     * 根据id查询数据
     *
     * @param id 物流跟踪的信息id
     * @return 查询到的单条物流的跟踪的信息
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "查询_Id", notes = "根据id获取到物流的跟踪的信息")
    public ResultDto findById(@ApiParam(value = "物流的跟踪id", required = true) @PathVariable Integer id) {
        OrdOrderTrackingDto dto = new OrdOrderTrackingDto();
        OrdOrderTracking entry = service.findById(id);
        if (entry != null) {
            EntityUtils.copyPropertiesIgnoreNull(entry, dto);
        }
        ResultDto result = new ResultDto();
        result.setData(dto);
        return result;
    }


    @RequestMapping(value = "/searchtypes", method = RequestMethod.GET)
    @ApiOperation(value = "查询_类型", notes = "获取到查询的类型")
    public ResultDto getSearchTypes() {
        List<SysDict> dictList = sysDictService.findByCatalog("ord.tracking.add.type");
        ResultDto dto = new ResultDto();
        dto.setData(dictList);
        return dto;
    }

    /**
     * 根据条件获取数据集合
     *
     * @param q         参数信息
     * @param pageIndex 哪页
     * @param pageSize  分页大小
     * @param sort      排序字段的名称
     * @param asc       true asc false desc
     * @return 查询的数据集合
     */
    @ApiOperation(value = "查询", notes = "根据指定条件获取数据集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "模糊查询参数", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页", dataType = "int", paramType = "query", defaultValue
                    = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数,max<2000", dataType = "int", paramType = "query",
                    defaultValue = "10"),
            @ApiImplicitParam(name = "sort", value = "排序的字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue =
                    "true")
    })
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResultDto find(@RequestParam(required = false) String q,
                          @RequestParam(required = false, defaultValue = "1") int pageIndex,
                          @RequestParam(required = false, defaultValue = "10") int pageSize,
                          @RequestParam(required = false) String sort,
                          @RequestParam(required = false, defaultValue = "true") Boolean asc
    ) {
        q = StringUtils.replaceSqlPattern(q);
        ResultDto result = service.findByParam(new QueryParams(pageSize, pageIndex, q, sort, asc));
        return result;
    }


    /**
     * 异步校验订单号或子订单号是否存在
     *
     * @param content 根据指定条件校验是否存在,可能是订单号、子订单号、航班号
     * @return　校验的结果
     */
    @ApiOperation(value = "异步校验参数是否存在", notes = "异步校验参数是否存在，可能是订单号、子订单号、航班号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "param", value = "要异步校验参数", required = true, dataType = "string", paramType = "query")})
    @RequestMapping(value = "/checkcontent", method = {RequestMethod.GET})
    public ResultDto checkContent(@RequestParam String content, @RequestParam int type) {
        service.checkLegal(type, content);
        return new ResultDto();
    }


}
